package com.finger.forest.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author jzj
 * @date 2020/10/5
 * @desc
 */
public class FileBitmapUtils {

    public static final String TAG = "FileBitmapUtils";
    public static final String ROOT_DIR = "/Forest";
    public static final String PICTURE = "/picture";

    /**
     * 保存Bitmap到图片文件
     * @param bmp
     * @param fileName
     * @return
     */
    public static String saveBitmapPicture(Bitmap bmp, String fileName, Context context) {
        Bitmap bitmap = createWatermark(bmp, DateUtil.dateToStr(DateUtil.DATE_FORMAT_MM_SS));//加水印
        FileOutputStream out = null;
        String filePath = null;
        try {
            // 获取SDCard指定目录下
            String sdCardDir = "data/data/" +AndroidUtil.getAppProcessName(context) + ROOT_DIR + PICTURE;
            File dirFile = new File(sdCardDir); //目录转化成文件夹
            if (!dirFile.exists()) { //如果不存在，那就建立这个文件夹
                dirFile.mkdirs();
            }
            File file = new File(sdCardDir, fileName);// 在SDcard的目录下创建图片文,以当前时间为其命名
            out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            Log.e(TAG, "saveBitmap: 图片保存到" + sdCardDir);
            out.flush();
            out.close();
            filePath = sdCardDir + "/"+ fileName;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }

    /**
     * 水印
     * @param bitmap
     * @param mark
     * @return
     */
    private static Bitmap createWatermark(Bitmap bitmap, String mark) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);
        Paint p = new Paint();
        // 水印颜色
        p.setColor(Color.parseColor("#ff0000"));
        // 水印字体大小
        p.setTextSize(15);
        //抗锯齿
        p.setAntiAlias(true);
        //绘制图像
        canvas.drawBitmap(bitmap, 0, 0, p);
        //绘制文字
        canvas.drawText(mark, 0, h/10*9, p);
        canvas.save();
        canvas.restore();
        return bmp;
    }

}
